//
//  NetWorkerManager.m
//  PublicInfo
//
//  Created by enghou on 2017/12/25.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

#import "NetWorkerManager.h"
#import "LocalPersistent.h"
#import "PropertyDictModel.h"
#import <AFNetworking.h>
#import "ProblemDetailModel.h"
@implementation NetWorkerManager{
    NSString *trueURL;
}

+(instancetype)sharedInstance{
    static NetWorkerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetWorkerManager alloc]init];
    });
    return manager;
}

-(void)configOtherURL:(NSString *)url{
    trueURL = url;
}

-(void)getCurrentPositionAndGridsSuccessBlock:(completeBlock)suc failBlock:(failBlock)fail{
    
}

-(NSString *)baseURL{
    return trueURL ? trueURL : ServerPath;
}

-(void)getStasticInfoWithUid:(NSString *)uid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param;
    if ([uid length] > 0) {
        param = @{@"orgCode":uid};
    }
    [self postWithPath:kGetStasticInfo parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getPersonalInfoWithCardId:(NSString *)cid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kGetPersonalInfoWithID parameter:@{@"population.idCardNo":cid} completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getProvincesSuccessBlock:(completeBlock)cmpt failBlock:(failBlock)fail{
    [self postWithPath:kProvince parameter:nil completeBlock:^(NSDictionary *source) {
        NSLog(@"%@",source);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getEventTypeSuccess:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kProblemEventType parameter:nil completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"TypeListModel")];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)handleProblemWithCode:(NSString *)code param:(NSDictionary *)param successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSString *path;
    if ([code isEqualToString:@"10"]) {
        path = kProblemHandle;
    }else if ([code isEqualToString:@"30"]){
        path = kProblemEnd;
    }else if ([code isEqualToString:@"50"]){
        path = kProblemUp;
    }else if ([code isEqualToString:@"70"]){
        path = kProblemFetchHandle;
    }else{
        path = kProblemBackHandle;
    }
    [self postWithPath:path parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)preHandleWithStepId:(NSString *)stepid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"issueStepId":stepid};
    [self postWithPath:kProblemPreHandle parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)problemDetailWithPid:(NSString *)pid stepId:(NSString *)stepId stepStatusCode:(NSString *)code successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"id":pid,@"issueStepId":stepId,@"stepSttusCode":code};
    [self postWithPath:kProblemDetail parameter:param completeBlock:^(NSDictionary *source) {
        ProblemDetailModel *model = [[ProblemDetailModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)commonAlertInterfaceWithPath:(NSString *)path parameter:(NSDictionary *)param successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:path parameter:param completeBlock:^(NSDictionary *source){
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:fail];
}

-(void)deleteProblemWithPid:(NSString *)pid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kProblemDelete parameter:@{@"id":pid} completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getPropertyDictWithDomainName:(NSString *)domainName successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"domainName":domainName};
    [self postWithPath:kGetPropertyDict parameter:param completeBlock:^(NSDictionary *source) {
        PropertyDictModel *model = [[PropertyDictModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"PropertyDictItemModel")];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)markReadWithId:(NSString *)item_id successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"messageIds[0]":item_id};
    [self postWithPath:kMarkRead parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getMailListWithPage:(NSInteger)page condition:(NSDictionary *)condition successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSMutableDictionary *param = [@{@"page":[NSString stringWithFormat:@"%i",page],@"rows":@"10"} mutableCopy];
    if (condition) {
        [param addEntriesFromDictionary:condition];
    }
    [self postWithPath:kMailList parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"MailBoxItemModel")];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)getMailListWithPage:(NSInteger)page successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    
}

-(void)getMailWithId:(NSString *)mid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"messageId":mid};
    [self postWithPath:kMailDetail parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)delMailWithId:(NSString *)mid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    NSDictionary *param = @{@"messageId":mid};
    [self postWithPath:kDelMail parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)queryMailTypeWithCondition:(NSDictionary *)condition successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kQueryMail parameter:condition completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"MessageTypeItemModel")];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)addNewPeopleInfoWithParam:(NSDictionary *)param successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kAddNewPeopleinfo parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)updatePeopleInfoWithParam:(NSDictionary *)param successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kUpdatePeopleinfo parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)deletePersonWithId:(NSString *)pid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kDeletePeopleinfo parameter:@{@"id":pid} completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}


-(void)getHousingInfoWithId:(NSString *)hid successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    [self postWithPath:kGetHousingInfo parameter:@{@"id":hid} completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)loginWithAccount:(NSString *)account password:(NSString *)pwd successBlock:(completeBlock)suc failBlock:(failBlock)fail{
    
    NSDictionary *param = @{@"userName":account,@"password":pwd};
    [self postWithPath:kLogin parameter:param completeBlock:^(NSDictionary *source) {
        NSDictionary *data = [source objectForKey:@"data"];
        NSString *sid = [data objectForKey:@"sid"];
        if (sid) {
            [[LocalPersistent sharedInstance]saveContent:sid forKey:@"sid"];
            [[LocalPersistent sharedInstance]saveContent:data[@"id"] forKey:@"uid"];
            [[LocalPersistent sharedInstance]saveContent:[NSString stringWithFormat:@"%@/%@",ServerPath,data[@"headerUrl"]] forKey:@"headimage"];
        }
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        suc(model);
    } failBlock:^(NSInteger code) {
        fail(code);
    }];
}

-(void)postWithPath:(NSString *)path parameter:(NSDictionary *)parameter completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@%@",[self baseURL],path];
    NSMutableDictionary *p;
    if (parameter) {
        p = [parameter mutableCopy];
        NSDate *now = [NSDate date];
        NSTimeInterval time = [now timeIntervalSince1970];
        NSInteger tim = time;
        NSString *ts = [NSString stringWithFormat:@"%li",tim];
        [p setObject:ts forKey:@"ts"];
        [p setObject:@"1.0" forKey:@"ver"];
        NSString *sid = [[LocalPersistent sharedInstance]contentForKey:@"sid"];
        if ([sid length] > 0) {
            if (![path isEqualToString:kLogin]) {
                [p setObject:sid forKey:@"sid"];
            }
        }
    }else{
        NSDate *now = [NSDate date];
        NSTimeInterval time = [now timeIntervalSince1970];
        NSInteger tim = time;
        NSString *ts = [NSString stringWithFormat:@"%li",tim];
        p = [@{@"ts":ts,@"ver":@"1.0"} mutableCopy];
        NSString *sid = [[LocalPersistent sharedInstance]contentForKey:@"sid"];
        if ([sid length] > 0) {
            if (![path isEqualToString:kLogin]) {
                [p setObject:sid forKey:@"sid"];
            }
        }
    }
    [manager POST:url parameters:p progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSDictionary *source = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            cmpt(source);
        }else{
            cmpt(@{});
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            fail(error.code);
        }
    }];
}

-(void)deleteWithPath:(NSString *)path parameter:(NSDictionary *)parameter completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@%@",[self baseURL],path];
    [manager DELETE:url parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSDictionary *source = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            cmpt(source);
        }else{
            cmpt(@{});
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            fail(error.code);
        }
    }];
}

-(void)getWithPath:(NSString *)path parameter:(NSDictionary *)parameter completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@%@",[self baseURL],path];
    NSMutableDictionary *p;
    if (parameter) {
        p = [parameter mutableCopy];
        NSDate *now = [NSDate date];
        NSTimeInterval time = [now timeIntervalSince1970];
        NSInteger tim = time;
        NSString *ts = [NSString stringWithFormat:@"%li",tim];
        [p setObject:ts forKey:@"ts"];
        [p setObject:@"1.0" forKey:@"ver"];
        NSString *sid = [[LocalPersistent sharedInstance]contentForKey:@"sid"];
        if ([sid length] > 0) {
            if (![path isEqualToString:kLogin]) {
                [p setObject:sid forKey:@"sid"];
            }
        }
    }else{
        NSDate *now = [NSDate date];
        NSTimeInterval time = [now timeIntervalSince1970];
        NSInteger tim = time;
        NSString *ts = [NSString stringWithFormat:@"%li",tim];
        p = [@{@"ts":ts,@"ver":@"1.0"} mutableCopy];
        NSString *sid = [[LocalPersistent sharedInstance]contentForKey:@"sid"];
        if ([sid length] > 0) {
            if (![path isEqualToString:kLogin]) {
                [p setObject:sid forKey:@"sid"];
            }
        }
    }
    [manager GET:url parameters:p progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSDictionary *source = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            cmpt(source);
        }else{
            cmpt(@{});
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            fail(error.code);
        }
    }];
}



-(void)uploadImageWithPath:(NSString *)path parameter:(NSDictionary *)parameter files:(NSArray *)files fileName:(NSString *)name suffix:(NSString *)suffix completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    if ([suffix length]==0) {
        fail(1);
        return;
    }
    NSString *type = [NSString stringWithFormat:@"image/%@",suffix];
    [self uploadFileWithPath:path parameter:parameter files:files fileNameKey:name contentType:type sufix:suffix completeBlock:cmpt failBlock:fail];
}

-(void)uploadAudeoWithPath:(NSString *)path parameter:(NSDictionary *)parameter files:(NSArray *)files fileName:(NSString *)name suffix:(NSString *)suffix completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    if ([suffix length]==0) {
        fail(1);
        return;
    }
    NSString *type = [NSString stringWithFormat:@"audio/%@",suffix];
    [self uploadFileWithPath:path parameter:parameter files:files fileNameKey:name contentType:type sufix:suffix completeBlock:cmpt failBlock:fail];
}

-(void)uploadVideoWithPath:(NSString *)path parameter:(NSDictionary *)parameter files:(NSArray *)files fileName:(NSString *)name suffix:(NSString *)suffix completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    if ([suffix length]==0) {
        fail(1);
        return;
    }
    NSString *type = [NSString stringWithFormat:@"video/%@",suffix];
    [self uploadFileWithPath:path parameter:parameter files:files fileNameKey:name contentType:type sufix:suffix completeBlock:cmpt failBlock:fail];
}

-(void)uploadFileWithPath:(NSString *)path parameter:(NSDictionary *)parameter files:(NSArray *)files fileNameKey:(NSString *)name contentType:(NSString *)cntType sufix:(NSString *)sufix completeBlock:(comptBlock)cmpt failBlock:(failBlock)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    NSDate *now = [NSDate date];
    NSInteger time = floor([now timeIntervalSince1970]);
    NSString *ts = [NSString stringWithFormat:@"%li",time];
    NSString *sid = [[LocalPersistent sharedInstance]contentForKey:@"sid"];
    NSString *url = [NSString stringWithFormat:@"%@%@?ts=%@&ver=1.0&sid=%@",[self baseURL],path,ts,sid];

    [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSData *data in files) {
            NSInteger index = [files indexOfObject:data];
            NSString *date = [[[NSDate date]dateStr] stringByAppendingString:[NSString stringWithFormat:@"%li",index]];
            NSString *fileName = [NSString stringWithFormat:@"%@.%@",[date md5],sufix];
            [formData appendPartWithFileData:data name:name fileName:fileName mimeType:cntType];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        NSError *error = nil;
        NSDictionary *source = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            cmpt(source);
        }else{
            cmpt(@{});
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            fail(error.code);
        }
    }];
}

@end
